﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace data
{
    public partial class Form1 : Form
    {
        private SqlConnection mycon;
        private SqlDataAdapter myada;
        private SqlCommand mycomd;
        private SqlCommandBuilder mycbd;
        private DataSet myset;
        public Form1()
        {
            InitializeComponent();
        mycon = new SqlConnection("Data Source=.;Initial Catalog=StudentCourse;Integrated Security=True");
        mycomd = new SqlCommand("select *from Student", mycon);
       myada = new SqlDataAdapter();
        myada.SelectCommand = mycomd;
            mycbd=new SqlCommandBuilder(myada);
             myset = new DataSet();
            myada.TableMappings.Add("Student", "Student");
            myada.TableMappings[0].ColumnMappings.Add("Sno", "学号");
            myada.TableMappings[0].ColumnMappings.Add("Sname", "姓名");
            myada.TableMappings[0].ColumnMappings.Add("Ssex", "性别");
            myada.TableMappings[0].ColumnMappings.Add("Sbirthady", "生日");
            myada.TableMappings[0].ColumnMappings.Add("Sdept", "院系");


        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                myada.Update(myset.Tables["Student"].GetChanges());
                MessageBox.Show("数据修改成功", "成功信息");
                myset.Tables["Student"].AcceptChanges();

            }
            catch(SqlException ex)
            {
                MessageBox.Show(ex.ToString());
            }

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                myada.Fill(myset, "Student");
            }
            catch (SqlException ex)
            {
                MessageBox.Show(ex.ToString());
            }
            finally
            {
                mycon.Close();
            }
            dataGridView1.DataSource = myset.Tables["Student"].DefaultView;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("确定要删除当行数据", "", MessageBoxButtons.OKCancel) == DialogResult.OK)
            {
                try
                {
                    myset.Tables[0].Rows[dataGridView1.CurrentRow.Index].Delete();
                    myada.Update(myset.Tables[0].GetChanges());
                    MessageBox.Show("数据删除成功！");
                    myset.Tables[0].AcceptChanges();
                }
                catch (SqlException ex)
                {
                    MessageBox.Show(ex.ToString());
                }
            }
            else
            {
                myset.Tables[0].RejectChanges();
            }
        }
    }
}
